package com.gan.springbootdemo.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Administrator on 2018/5/10
 * Http网络请求工具类
 */
@Slf4j
public class HttpUtil {
    /**
     * POST请求获取json字符串
     *
     * @param urlStr    urlStr
     * @param paramStr  paramStr
     * @return String
     */
    public static String post(String urlStr, String paramStr) {
        final StringBuilder builder = new StringBuilder();
        HttpURLConnection httpURLConnection = null;
        try {
            final URL url = new URL(urlStr);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            // 设置关键值
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setConnectTimeout(20 * 1000);
            httpURLConnection.setReadTimeout(20 * 1000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setUseCaches(false);
            // 设置请求头信息
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.connect();
            // post参数
            if (paramStr != null) {
                PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"));
                printWriter.write(paramStr);
                printWriter.flush();
            }
            // 读取响应码
            if (httpURLConnection.getResponseCode() == 200) {
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    builder.append(line);
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return builder.toString();
    }

}